package com.ryskoo.util;


import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.im4java.core.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * 图片工具类
 *
 * @author Shawn
 */
public class ImageUtils {
    private static final Logger logger = LogManager.getLogger(ImageUtils.class);

    // 图片质量
    public static final String IMAGE_QUALITY = "quality";
    // 图片高度
    public static final String IMAGE_HEIGHT = "height";
    // 图片宽度
    public static final String IMAGE_WIDTH = "width";
    // 图片格式
    public static final String IMAGE_SUFFIX = "suffix";
    // 图片大小
    public static final String IMAGE_SIZE = "size";
    // 图片路径
    public static final String IMAGE_PATH = "path";

    /**
     * 使用GraphicsImagick
     */
    private static final boolean USE_GRAPHICS_MAGICK = true;

    /**
     * 服务器上 gm 命令所在目录
     */
    private static final String GRAPHICS_MAGICK_PATH = "C:/Program Files/GraphicsMagick-1.3.28-Q16";

    /**
     * 水印图片路径
     */
//    private static final String watermarkImagePath = "/Users/gary/Documents/Job/ImageProcessTool/Im4java/Linux_logo.jpg";
    private static final String watermarkImagePath = "F:/image/dd.jpg";
    
    /**
     * 水印图片
     */
    private static Image watermarkImage = null;

    // 加载水印图片
    static {
        try {
            watermarkImage = ImageIO.read(new File(watermarkImagePath));
        } catch (IOException e) {
            logger.error("读取水印图片失败", e);
        }
    }

    /**
     * 命令类型
     */
    private enum CommandType {
        /**
         * 图片转换处理
         */
        convert("转换处理"),
        /**
         * 获取图片信息
         */
        identify("图片信息"),
        /**
         * 图片合成
         */
        compositecmd("图片合成");
        private String name;

        CommandType(String name) {
            this.name = name;
        }
    }

    /**
     * 获取 ImageCommand
     *
     * @param command 命令类型
     * @return 图片操作命令
     */
    private static ImageCommand getImageCommand(CommandType command) {
        ImageCommand cmd = null;
        switch (command) {
            case convert:
                cmd = new ConvertCmd(USE_GRAPHICS_MAGICK);
                break;
            case identify:
                cmd = new IdentifyCmd(USE_GRAPHICS_MAGICK);
                break;
            case compositecmd:
                cmd = new CompositeCmd(USE_GRAPHICS_MAGICK);
                break;
            default:
        }
        // windows系统需要设置，linux不需要，如果设置了会报错
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")) {
            cmd.setSearchPath(GRAPHICS_MAGICK_PATH);
        }
        return cmd;
    }

    /**
     * 按照比例缩放且压缩图片
     * 
     * @param srcImagePath 源图片路径 
     * @param destImagePath 目标图片路径 
     * @param width 压缩后的宽 
     * @param height 压缩后的高 
     * @param quality 压缩质量（0-100） 
     * @return 
     */  
    public static void resizeImage(String srcImagePath, String destImagePath, Integer width, Integer height, Double quality){
    	IMOperation op = new IMOperation();
        op.addImage(srcImagePath);
        op.quality(quality);
        // 判断宽高
        if (width == null) {
            // 根据高度缩放图片
            op.resize(null, height);
        } else if (height == null) {
            // 根据宽度缩放图片
            op.resize(width);
        } else {
            op.resize(width, height);
        }
        op.addImage(destImagePath);
        ImageCommand cmd = getImageCommand(CommandType.convert);
        try {
            cmd.run(op);
        } catch (IOException e) {
            logger.error("读写图片错误", e);
        } catch (InterruptedException e) {
            logger.error("压缩图片进程意外终止", e);
        } catch (IM4JavaException e) {
            logger.error("图片压缩失败", e);
        }
    }  
    
    /**
     * 根据图片总路径，取得文件名和文件前缀和文件后缀
     */
    public static String[] getFilePreAndSufName(String baseImg){
    	String[] file = new String[3];
    	if(!StringUtils.isEmpty(baseImg)){
    		String[] baseFiles = baseImg.split("/");
    		// 文件名 
    		String baseImgName = baseFiles[baseFiles.length-1];
    		int pos = baseImgName.lastIndexOf(".");
    		// 前缀
    		String prefix = "";
    		// 后缀
			String suffix = "";
    		if (pos < 0) {
    			prefix = baseImgName;
    		} else {
    			prefix = baseImgName.substring(0, pos);
    			suffix = baseImgName.substring(pos+1);
    		}
    		file[0] = baseImgName;
    		file[1] = prefix;
    		file[2] = suffix;
    	}
    	return file;
    }

}
